/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bibliOnline.db;

/**
 *
 * @author luca
 */
import java.sql.*;
import bibliOnline.util.details.BookDetails;

public class BookInserter {

    public static void insert(BookDetails book) throws Exception {
        PreparedStatement statement;
        String sql;

        try {
            sql = "INSERT INTO BOOK (AUTHOR, TITLE, PUBLISHER, EDITION, GENRE, YEAR) "
                    + "VALUES (?, ?, ?, ?, ?, ?)";

            statement = DBConnection.prepareStatement(sql);

            statement.setString(1, book.getAuthor());
            statement.setString(2, book.getTitle());
            statement.setString(3, book.getPublisher());
            statement.setString(4, book.getEdition());
            statement.setString(5, book.getGenre());
            statement.setInt(6, book.getYear());

            statement.executeUpdate();

            statement.close();
        } catch (Exception ex) {
            throw new Exception(ex.getMessage());
        }
    }

    public static boolean exists(BookDetails book) throws Exception {
        PreparedStatement statement;
        ResultSet result;
        String sql;
        boolean exists;
        exists = false;

        try {
            sql = "SELECT AUTHOR, TITLE, PUBLISHER, EDITION, GENRE, YEAR "
                    + "FROM BOOK "
                    + "WHERE AUTHOR = ? AND TITLE = ? AND PUBLISHER = ? "
                    + "AND EDITION = ? AND GENRE = ? AND YEAR = ?";

            statement = DBConnection.prepareStatement(sql);

            statement.setString(1, book.getAuthor());
            statement.setString(2, book.getTitle());
            statement.setString(3, book.getPublisher());
            statement.setString(4, book.getEdition());
            statement.setString(5, book.getGenre());
            statement.setInt(6, book.getYear());

            result = statement.executeQuery();

            if (result.next()) {
                exists = true;
            }

            statement.close();
        } catch (Exception ex) {
            throw new Exception(ex.getMessage());
        }

        return exists;
    }
}
